package com.fingard.dsp.bank.directbank.bocom13;


import com.allinpay.ets.client.StringUtil;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.IContract;
import com.fingard.dsp.bank.reqrespobj.contract.*;
import com.fingard.dsp.bank.reqrespobj.contract.detail.RetAtsContractDetail;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.util.Date;

/**
 * 交行资金清算平台单笔代扣签约
 * <p>
 * 参考文档:
 * 1、交通银行资金清算平台联机交易接口V1.0.doc
 * 2、交通银行资金清算平台数据字典V1.0.doc
 */
public class BOCOM13Contract extends BOCOM13Base implements IContract {
    /**
     * 开发接口:4.1    代收签约
     */
    String tmpBusDate = "BusDate";
    String tmpSeqNo = "SeqNo";
    String tmpSignConfirm = "signConfirm";

    @Override
    public RetAtsContract contract(ReqContract p_req) throws Exception {
        RetAtsContract retAts = new RetAtsContract(p_req.reqHeader);
        RetAtsContractDetail tmpRetDetail = new RetAtsContractDetail();
        tmpRetDetail.reqSeqID = p_req.contractDetail.askNumber;

        try {
            BOCOM13Header tmpBankHeader = new BOCOM13Header();
            tmpBankHeader.reqSeqID = p_req.contractDetail.askNumber;
            String corpNo = getBankConfig().getMapValueByKey("corpNoMapping", p_req.contractDetail.recAct);
            if (StringHelper.isNullOrEmpty(corpNo)) {
                tmpRetDetail.respCode = "0";
                tmpRetDetail.respInfo = "未找到账号[" + p_req.contractDetail.recAct + "]保险方ID映射,请检查BOCOM13/config.xml中'corpNoMapping'节点配置";
                tmpRetDetail.signState = ContractState.FAIL;
                retAts.writeRetDetail(tmpRetDetail);
                return retAts;
            }
            tmpBankHeader.corpNo = corpNo;
            XmlTextWriter xmlWriter = new XmlTextWriter();
            if ("02".equals(p_req.contractDetail.step)) {
                tmpBankHeader.transCode = "I00408";
                writeCommonHeader(xmlWriter, tmpBankHeader);
                xmlWriter.writeStartElement("Body");
                xmlWriter.writeElementString(tmpBusDate, Format.Date8Format.format(new Date()));/* 保险方业务日期 */
                xmlWriter.writeElementString(tmpSeqNo, tmpBankHeader.reqSeqID);/* 保险方流水号 */
                xmlWriter.writeElementString("OriSeqNo", p_req.contractDetail.askNumber);/* 签约申请的流水号 	*/
                xmlWriter.writeElementString("IdentifyCode", p_req.contractDetail.smsCode);/* 签约申请的流水号 	*/
                xmlWriter.writeElementString("Ext001", "");
                xmlWriter.writeElementString("Ext002", "");
                xmlWriter.writeElementString("Ext003", "");
                xmlWriter.writeElementString("Ext004", "");
                xmlWriter.writeElementString("Ext005", "");
                xmlWriter.writeElementString("Ext006", "");
                xmlWriter.writeElementString("Ext007", "");
                xmlWriter.writeElementString("Ext008", "");
                xmlWriter.writeElementString("Ext009", "");
                xmlWriter.writeElementString("Ext010", "");
                xmlWriter.writeEndDocument();
            } else {

                if ("2".equals(getBankConfig().getValueAsString(tmpSignConfirm))) {
                    tmpBankHeader.transCode = "I00407";
                } else if ("3".equals(getBankConfig().getValueAsString(tmpSignConfirm))) {
                    tmpBankHeader.transCode = "I00401";
                } else {
                    tmpRetDetail.respCode = "-1";
                    tmpRetDetail.respInfo = "请检查节点配置：" + tmpSignConfirm;
                    retAts.writeRetDetail(tmpRetDetail);
                    return retAts;
                }
                writeCommonHeader(xmlWriter, tmpBankHeader);
                xmlWriter.writeStartElement("Body");
                xmlWriter.writeElementString(tmpBusDate, Format.Date8Format.format(new Date()));/* 保险方业务日期 */
                xmlWriter.writeElementString(tmpSeqNo, tmpBankHeader.reqSeqID);/* 保险方流水号 */
                if (StringHelper.hasAnyChar(p_req.contractDetail.sourceNoteCode)) {
                    xmlWriter.writeElementString("ApplyNo", p_req.contractDetail.sourceNoteCode);/* 投保单号 */
                } else {
                    xmlWriter.writeElementString("PolNo", p_req.contractDetail.insuPolicyNum);/* 保单号 */
                }
                xmlWriter.writeElementString("Name", p_req.contractDetail.payName);/* 客户姓名 */
                xmlWriter.writeElementString("IdType", convertCertTypeToBank(p_req.contractDetail.certType));/* 证件类型 */
                xmlWriter.writeElementString("IdNo", p_req.contractDetail.certNum);/* 证件号码 */
                xmlWriter.writeElementString("Telephone", p_req.contractDetail.cellPhone);/* 手机号码 */
                String isPrivate = "";
                if (StringHelper.hasAnyChar(p_req.contractDetail.isPrivate)) {
                    if ("1".equals(p_req.contractDetail.isPrivate)) {
                        isPrivate = "P";
                    } else {
                        isPrivate = "E";
                    }
                } else {
                    isPrivate = "P";
                }
                xmlWriter.writeElementString("EpFlag", isPrivate);/* 公私标志(E-对公,P-对私) */
                xmlWriter.writeElementString("PrdName", "");/* 险种名称 */
                xmlWriter.writeElementString("ActNo", p_req.contractDetail.payAct);/* 账号 */
                xmlWriter.writeElementString("CurType", "CNY");/* 交易币种 */
                String BusType = getBankConfig().getMapValueByKey("contractBusiCode", p_req.contractDetail.busType);
                if ("I00407".equals(tmpBankHeader.transCode)) {
                    xmlWriter.writeElementString("BusType", BusType);/* 交易币种 */
                } else {
                    xmlWriter.writeElementString("BusType", "D10");/* 收付种类:D10-首期缴费(2.42收付种类) */
                }
                xmlWriter.writeElementString("Ext001", "");
                xmlWriter.writeElementString("Ext002", "");
                xmlWriter.writeElementString("Ext003", "");
                xmlWriter.writeElementString("Ext004", "");
                xmlWriter.writeElementString("Ext005", "");
                xmlWriter.writeElementString("Ext006", "");
                xmlWriter.writeElementString("Ext007", "");
                xmlWriter.writeElementString("Ext008", "");
                xmlWriter.writeElementString("Ext009", "");
                xmlWriter.writeElementString("Ext010", "");
                xmlWriter.writeEndDocument();
            }
            String[] tmpRetStr = sendToBank(xmlWriter.toXmlString(), bankFront.serverPort);
            if (tmpRetStr[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpRetStr[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    tmpRetDetail.respCode = "0";
                    tmpRetDetail.respInfo = tmpBkReader.getFirstText("/Rsp/Head/ErrMsg");
                    String tmpMsgType = tmpBkReader.getFirstText("/Rsp/Head/MsgType");
                    String tmpErrCode = tmpBkReader.getFirstText("/Rsp/Head/ErrCode");
                    String signno = tmpBkReader.getFirstText("/Rsp/Body/AgreementNo");
                    if ("01".equals(p_req.contractDetail.step)) {
                        if (!"N".equals(tmpMsgType)) {
                            tmpRetDetail.respCode = "-1";
                        }
                        if ("000000".equals(tmpErrCode) && !StringUtil.isEmpty(signno)) {
                            tmpErrCode = "3068";
                            tmpRetDetail.authCode = signno;
                        }
                        tmpRetDetail.signConfirmType = this.getBankConfig().getValueAsString(tmpSignConfirm);
                    } else {
                        String Stats = tmpBkReader.getFirstText("/Rsp/Body/Stats");
                        String ErrMsg = tmpBkReader.getFirstText("/Rsp/Body/ErrMsg");
                        if ("1".equals(Stats) || "200077".equals(tmpErrCode)) {
                            // 签约状态: 0-处理中 1-成功 2-失败
                            tmpRetDetail.signState = ContractState.SUCCESS;
                            tmpRetDetail.authCode = signno;
                            tmpRetDetail.newAuthCode = signno;
                        } else if ("2".equals(Stats)) {
                            tmpRetDetail.respInfo = ErrMsg;
                            tmpRetDetail.signState = ContractState.FAIL;
                        } else if ("0".equals(Stats)) {
                            tmpRetDetail.signState = ContractState.SIGNING;
                            tmpRetDetail.respInfo = ErrMsg;
                        } else {
                            tmpRetDetail.respCode = "-1";
                            tmpRetDetail.respInfo = ErrMsg;
                        }
                    }
                    tmpRetDetail.unifiedCode = getBankConfig().getMapValueByKey("contractMapping", tmpErrCode);
                } else {
                    tmpRetDetail.respCode = "-1";
                    tmpRetDetail.respInfo = tmpSbMsg.toString();
                }
            } else {
                tmpRetDetail.respCode = "-1";
                tmpRetDetail.respInfo = tmpRetStr[1];
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            tmpRetDetail.respCode = "-1";
            tmpRetDetail.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }
        retAts.writeRetDetail(tmpRetDetail);
        return retAts;
    }

    @Override
    public RetAtsContract upContract(ReqContract p_req) throws Exception {
        return null;
    }

    /**
     * 开发接口:4.3	代收签约交易查证（I00403）
     */
    @Override
    public RetAtsContract qryContract(ReqContract p_reqQry) throws Exception {
        RetAtsContract retAts = new RetAtsContract(p_reqQry.reqHeader);
        RetAtsContractDetail tmpRetDetail = new RetAtsContractDetail();
        tmpRetDetail.reqSeqID = p_reqQry.contractDetail.askNumber;

        try {
            BOCOM13Header tmpBankHeader = new BOCOM13Header();
            tmpBankHeader.transCode = BOCOM13TransCode.realTime_QryContract_9108Auth;
            tmpBankHeader.reqSeqID = p_reqQry.contractDetail.askNumber;
            String corpNo = getBankConfig().getMapValueByKey("corpNoMapping", p_reqQry.contractDetail.recAct);
            if (StringHelper.isNullOrEmpty(corpNo)) {
                tmpRetDetail.respCode = "-1";
                tmpRetDetail.respInfo = "未找到账号[" + p_reqQry.contractDetail.recAct + "]保险方ID映射,请检查BOCOM13/config.xml中'corpNoMapping'节点配置";
                retAts.writeRetDetail(tmpRetDetail);
                return retAts;
            }
            tmpBankHeader.corpNo = corpNo;

            XmlTextWriter xmlWriter = new XmlTextWriter();
            writeCommonHeader(xmlWriter, tmpBankHeader);
            xmlWriter.writeStartElement("Body");
            if (StringHelper.hasAnyChar(p_reqQry.contractDetail.bookDate)) {
                xmlWriter.writeElementString(tmpBusDate, p_reqQry.contractDetail.bookDate);
            } else {
                xmlWriter.writeElementString(tmpBusDate, Format.Date8Format.format(new Date()));
            }
            xmlWriter.writeElementString(tmpSeqNo, tmpBankHeader.reqSeqID);
            xmlWriter.writeEndDocument();

            String[] tmpRetStr = sendToBank(xmlWriter.toXmlString(), bankFront.serverPort);

            if (tmpRetStr[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpRetStr[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    tmpRetDetail.respCode = "0";
                    tmpRetDetail.respInfo = tmpBkReader.getFirstText("/Rsp/Head/ErrMsg");

                    String tmpMsgType = tmpBkReader.getFirstText("/Rsp/Head/MsgType");
                    String tmpErrCode = tmpBkReader.getFirstText("/Rsp/Head/ErrCode");
                    if ("N".equals(tmpMsgType) && "000000".equals(tmpErrCode)) {
                        // 签约状态: 0-处理中 1-成功 2-失败 3-超时
                        String signStatus = tmpBkReader.getFirstText("/Rsp/Body/AgreementStat");
                        if ("1".equals(signStatus)) {
                            tmpRetDetail.signState = ContractState.SUCCESS;

                            String authCode = tmpBkReader.getFirstText("/Rsp/Body/AgreementNo");/* 代收协议编号 */
                            tmpRetDetail.authCode = authCode;
                            tmpRetDetail.newAuthCode = authCode;
                        } else if ("2".equals(signStatus)) {
                            tmpRetDetail.signState = ContractState.FAIL;
                        } else {
                            tmpRetDetail.signState = ContractState.SIGNING;
                        }
                    } else if ("E".equals(tmpMsgType) && "200069".equals(tmpErrCode)) {
                        tmpRetDetail.respCode = "0";
                        tmpRetDetail.signState = ContractState.UNSIGNED;
                        tmpRetDetail.respInfo = "记录不存在";
                    } else if ("E".equals(tmpMsgType) && "200018".equals(tmpErrCode)) {
                        tmpRetDetail.respCode = "0";
                        tmpRetDetail.signState = ContractState.UNSIGNED;
                        tmpRetDetail.respInfo = "流水号为空";
                    } else {
                        tmpRetDetail.respCode = "-1";
                    }
                    tmpRetDetail.signConfirmType = this.getBankConfig().getValueAsString(tmpSignConfirm);
                } else {
                    tmpRetDetail.respCode = "-1";
                    tmpRetDetail.respInfo = tmpSbMsg.toString();
                }
            } else {
                tmpRetDetail.respCode = "-1";
                tmpRetDetail.respInfo = tmpRetStr[1];
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            tmpRetDetail.respCode = "-1";
            tmpRetDetail.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }

        retAts.writeRetDetail(tmpRetDetail);
        return retAts;
    }

    @Override
    public RetAtsQryBatContract qryBatContract(ReqQryBatContract p_reqQry) throws Exception {
        return null;
    }

}
